function UdpServer(){
    const dgram = require('dgram');
    class UdpServer {
        static _get={};
        static OnRecive=(req,res)=>{
            console.log(req)
        }
        constructor() {
            this.server = dgram.createSocket('udp4');
            this.remotePort=0;
            this.remoteIp=0;
            this.port=0;
            this.install();
        }

        get(url, callback) {
            UdpServer._get[url]=callback;
        }

        begin(beginFun) {
            UdpServer.OnRecive=beginFun;
        }

        listen(port){
            this.port=port;
            this.server.bind(port);

        }
        send(v,remoteIp,remotePort) {
            if(remoteIp){
                this.remoteIp=remoteIp;
            }
            if(remotePort){
                this.remoteIp=remotePort;
            }
            if(Array.isArray(v)){
                v=new Buffer(v)
            }
            this.server.send(v,this.remotePort,this.remoteIp)
        }

        install(app,server){
            let that=this;
            this.server.on('close',()=>{
                console.log('udp close');
            });

            this.server.on('error',(err)=>{
                console.log(err);
            });

            this.server.on('listening',()=>{
                console.log('udp listen on '+that.port);
            });
            this.server.on('message',(msg,rinfo)=>{
                that.remoteIp=rinfo.address;
                that.remotePort=rinfo.port;
                let req={}
                req.ip=rinfo.address;
                req.port=rinfo.port;
                req.params=msg;
                let res=that;
                UdpServer.OnRecive(req,res);
            });

        }
    }
    return new UdpServer();
}


module.exports =  UdpServer;